<?php
require_once dirname(__FILE__) . '/../includes/common.inc.php';
require_once dirname(__FILE__) . '/../includes/pdoorm.inc.php';

header('Content-Type: text/plain');


$class = MiscUtils::getParam('name', NULL);
$objectsToAddOrUpdate = json_decode(MiscUtils::getParam('obj', NULL));
$objectsToRemove = json_decode(MiscUtils::getParam('r', NULL));

/*echo $class;
print_r($objectsToAddOrUpdate);
print_r($objectsToRemove);
die;*/


    foreach ($objectsToAddOrUpdate as &$object) {
      if (isset($object->id) || isset($object->e_oid)) {
        
          switch($class){
            case'v1sample_u':
            {
                $class = 'v1sample';
                pdov1sampleupdate($object,$class);
            }
                break;
                
            case'v1package':
                pdov1packageupdate($object,$class);
                break;
                
            case'v1customer':
            case'customer':
            	{
            	   $class = 'v1customer';
                   pdov1customerupdate($object,$class);
            	}
                break;
                
            case'customerecn':    
            	{
            		$class = 'v1customer';
            		pdov1customerupdate($object,$class,'',true);
            	}
                break;
            	
            case'v1myorder':
                pdov1myorderupdate($object,$class);
                break; 

            case'paymentadd':
                paymentadd($object,$class);
                break;                  
                
            case'v1myorder_close':
            {
                $class = 'v1myorder';
                pdov1myorderclose($object,$class);
            }
                break;  
                
            case'v1payment':
                pdov1paymentadd($object,$class);
                break;  
                
            case'v1payment_c':
            {
                $class = 'v1payment';
                pdov1paymentupdate($object,$class);//cancel
            }
                break;  
                
            case'payment_note':
            {
                $class = 'v1payment';
                pdov1paymentnoteupdate($object,$class);
            }
                break;                  
                
            case'expense_c':
            {
                $class = 'expense';
                pdoexpenseupdate($object,$class);//cancel
            }
                break;  
                
            case'expense':
            {
                $class = 'expense';
                pdoexpenseupdateall($object,$class);//cancel
            }
                break;                  

            case'purchaseitem':
            {
                pdopurchaseitemupdate($object,$class);//cancel
            }
                break;                      
                
            case'v1purchasenote':
                pdopurchasenote($object,$class);
                break;
                    
            default:
                pdoupdate($object,$class);
                break;  
        
          }
        
      } else {
              switch($class){
                case'v1sample':
                    pdov1sampleadd($object,$class);
                    break;
                    
                case'v1package':
                    pdov1packageadd($object,$class);
                    break;                  

                case'v1customer':
                    pdov1customeradd($object,$class);
                    break;

                case'expense':
                    pdoexpenseadd($object,$class);
                    break;                          

                case 'myordernote':
                	myordernoteadd($object,$class);
                	break;    
                	
                case 'sendemail':
                    sendemail($object,$class);
                    break;                   	
                    
                default:
                     pdoadd($object,$class);
                    break;  
              }         
       
      }
    }
    
    foreach ($objectsToRemove as &$object) {
      
          switch($class){
            case'v1sample':
                pdov1samplemove($object,$class);
                break;
                
            case'v1package':
                pdov1packagemove($object,$class);
                break;              
                
            default:
                pdoremove($object,$class);
                break;  
        
          }      
    }


function pdoadd($obj,$class){
    
    $addsql="insert into ns_".$class."  values(NULL,";
    
    foreach ($obj as $key => $value){
        
            switch($class){
                case'datezone':
                    {
                        if( in_array($key,array('start','end') ) ) $value = SimpleDate::toStamp($value); //format date
                    }
                    break;
                case'payment':
                    {
                        if( in_array($key,array('createdDate','date','cancelledDate') ) ) $value = SimpleDate::toStamp($value); //format date
                    }
                    break;                  
                
            }
                
       $addsql.=" '".addslashes($value)."',";
    }

    $addsql =substr($addsql,0,-1);
    $addsql.=")";

    sql_execute($addsql);
}


function pdov1sampleadd($obj,$class,$debug=''){

    if(!empty($debug)){
      print_r($obj);
      echo"\n";
    }
   
    $addsql ="insert into ns_".$class." (e_oid,trackId,name,price,unit,type,model) values(NULL,'".$obj->trackId."','".addslashes($obj->name)."','".$obj->price."','".$obj->unit."','".$obj->type."','".$obj->model."')";
    if(!empty($debug))
    {
        echo $addsql."\n";
    }else{
        sql_execute($addsql);
        $parentId0 = lastinsertid();
    }
    
    foreach($obj->attributes as $ars){
        $addsql0 ="insert into ns_".$class."attribute (e_oid,name,sample_id) values(NULL,'".addslashes($ars->name)."','".$parentId0."')";
        if(!empty($debug))
        {
            echo $addsql0."\n";
        }else{
            sql_execute($addsql0);
            $parentId1 = lastinsertid();    
        }
        foreach($ars->options as $ops){
            $addsql1 ="insert into ns_".$class."attributeoption (e_oid,name,sampleattribute_id) values(NULL,'".addslashes($ops->name)."','".$parentId1."')";
            if(!empty($debug))
            {
               echo $addsql1."\n";
            }else{
              sql_execute($addsql1);
            }
            
        }
        
    }
}

/* 
 *  sample update
 *
 */
 
   function pdov1sampleupdate($obj,$class,$debug='')
   {
        if(!empty($debug))
        {
            print_r($obj);      
        }

         if(!empty($obj))
         {
             $samplesql = "update ns_".$class." set  trackId = '".$obj->trackId."',
                                                     name = '".$obj->name."',
                                                     price = '".$obj->price."',
                                                     unit = '".$obj->unit."',
                                                     type = '".$obj->type."',
                                                     model = '".$obj->model."'
                                                 where e_oid = '".$obj->e_oid."'";
                                                 
             if (!empty($debug))
             { 
                 echo $samplesql."\n";
             }else{
                 sql_execute($samplesql);
                 $sample_id = $obj->e_oid;               
             }           
             
             
             /*
              * sampleattribure  delete
              *
              */
              
             if(!empty($obj->attributes))
             {
             
                $original_sampleattribute_id = getsonid('ns_v1sampleattribute','e_oid','sample_id',$obj->e_oid);//原来的ns_v1sampleattribute数组
                 
                if(!empty($debug))
                {
                   print_r($original_sampleattribute_id); 
                }       
             
               $new_sampleattribute_id = array();
               
               foreach($obj->attributes as $sattribute1)
               {
                    $new_sampleattribute_id[] = $sattribute1->e_oid;
               }

               $delete_soption_id = array_diff($original_sampleattribute_id, $new_sampleattribute_id);//需要delete 的sampleattribute_id
               
               if(!empty($delete_soption_id))
               {
                    foreach($delete_soption_id as $deleteid)
                    {
                         $soption_id = getsonid('ns_v1sampleattributeoption','e_oid','sampleattribute_id',$deleteid); 
                         
                              if(!empty($soption_id))
                               {                          
                                     foreach($soption_id as $pid)
                                     {
                                         $soptionsql = "delete from ns_v1sampleattributeoption where e_oid = '".$pid."' ";
                                         sql_execute($soptionsql); 
                                     }
                               }//
                            
                        $sampleattributesql = "delete from ns_v1sampleattribute where e_oid = '".$deleteid."' ";
                        sql_execute($sampleattributesql);                       
                    
                    }
                }//delete sampleattribute end
                              
              
              
              /*
               *update or add
               *
               */
               
               foreach($obj->attributes as $sattribute)
               {
                     if (isset($sattribute->e_oid) || isset($sattribute->id))
                     {//update
                         
                         $sampleattributesql =  "update ns_v1sampleattribute set name = '".$sattribute->name."',
                                                                                 sample_id = '".$sample_id."' 
                                                                           where e_oid = '".$sattribute->e_oid."'";
                          if (!empty($debug))
                          {
                             echo $sampleattributesql."\n";
                          }else{
                             sql_execute($sampleattributesql);
                             $sampleattribute_id = $sattribute->e_oid;                       
                          }                                                                        
                         
                         
                     }else{//add
                          $sampleattributesql ="insert into ns_".$class."attribute (e_oid,name,sample_id) values(NULL,'".addslashes($sattribute->name)."','".$sample_id."')";
                           if(!empty($debug))
                           {
                                echo $sampleattributesql."\n";
                           }else{
                                sql_execute($sampleattributesql);
                                $sampleattribute_id = lastinsertid();   
                           }                     
                     } 
                    
                    /*
                     *option 
                     *
                     */      

                     if(!empty($sattribute))
                     {
                     	/**
                     	 * delete options start
                     	 */
			                $original_options_id = getsonid('ns_v1sampleattributeoption','e_oid','sampleattribute_id',$sattribute->e_oid);//原来的ns_v1sampleattributeoptins数组
			                 
			                if(!empty($debug))
			                {
			                   print_r($original_options_id); 
			                }       
			             
			               $new_options_id = array();
			               
			               foreach($sattribute->options as $soptions1)
			               {
			                    $new_options_id[] = $soptions1->e_oid;
			               }
			
			               $delete_options_id = array_diff($original_options_id, $new_options_id);//需要delete 的sampleattribute_id
			               
			               if(!empty($delete_options_id))
			               {
			                    foreach($delete_options_id as $deloptionid)
			                    {
			                            
			                        $deloptionsql = "delete from ns_v1sampleattributeoption where e_oid = '".$deloptionid."'";
			                        sql_execute($deloptionsql);                       
			                    
			                    }
			                }//delete sampleattribute end                     	
                     	
                     	/**
                     	 * delete options end
                     	 */
                     	
                         foreach($sattribute->options  as $soption)
                         {
                             if (isset($soption->e_oid) || isset($soption->id))
                             {//update
                                 $sampleattributeoptionsql = "update ns_v1sampleattributeoption set name = '".$soption->name."',
                                                                                                    sampleattribute_id = '".$sampleattribute_id."'
                                                                                               where e_oid = '".$soption->e_oid."'";
                                                                                               
                                  if (!empty($debug))
                                  {
                                     echo $sampleattributeoptionsql."\n";
                                  }else{
                                      sql_execute($sampleattributeoptionsql); 
                                  } 

                                  
                             }else{//add
                                 $sampleattributeoptionsql ="insert into ns_".$class."attributeoption (e_oid,name,sampleattribute_id) values(NULL,'".addslashes($soption->name)."','".$sampleattribute_id."')";
                                 if(!empty($debug))
                                 {
                                     echo $sampleattributeoptionsql."\n";
                                 }else{
                                      sql_execute($sampleattributeoptionsql);
                                 }            
                             }
                         }
                     
                     }//option not null

                     
                }

            }//attribute not null              
             
             
         }//not null
   }




function pdov1packageadd($obj,$class,$debug=''){

	if(!empty($debug))
	{
		print_r($obj);
	}
	
     $addsql=" insert into ns_".$class." (`e_oid`,`trackId`,`name`,`price`,`hours`,`persons`,`makeup`,`type`,`orderInc`) values
                                         (NULL,'".$obj->trackId."','".$obj->name."','".$obj->price."','".$obj->hours."',
                                          '".$obj->persons."','".$obj->makeup."','".$obj->type."','".$obj->orderInc."')";
     
     if(!empty($debug))
     {
     	echo $addsql."\n";
     	$parentId0 = 0;
     }else{
        sql_execute($addsql);
        $parentId0 = lastinsertid();
     }
 
     if(!empty($obj->packageItems))
     {
		     foreach($obj->packageItems as $piv){
		        $addsql0="insert into ns_".$class."item (`e_oid`,`trackId`,`quantity`,`total`,`otherId`,`sample_id`,`package_id`) values 
		                                                (NULL,'".$piv->trackId."','".$piv->quantity."','".$piv->total."',
		                                                '".$piv->otherId."','".$piv->sample->id."','".$parentId0."')";
		        if(!empty($debug))
		        {
		           echo $addsql0."\n";
		           $parentId1 = 0;	
		        }else{
		           sql_execute($addsql0);
		           $parentId1 = lastinsertid();    
		        }
		        
		        
		       if(!empty($piv->sample->attributes))
		       { 
		       	    if(!empty($piv->selects))
		       	    {
				        foreach($piv->selects as $pisv){
				            $addsql1="insert into ns_".$class."itemselect(`e_oid`,`trackId`,`title`,`value`,`packageitem_id`) values
				                                                         (NULL,'".$pisv->trackId."','".$pisv->title."','".$pisv->value."','".$parentId1."')";
				            if(!empty($debug))
				            {
				            	echo $addsql1."\n";
				            }else{
				                sql_execute($addsql1);
				            }
				        }
			        
		       	    }
			        
		       }// 只有当产品有属性的时候才能有select
		        
		     }
		     
     }//$obj->packageItems   not null
}


/*
 *package update
 */  
    function pdov1packageupdate($obj,$class,$debug='')
    {
        if(!empty($debug))
        {
            print_r($obj);                
        }
        
                      
        if(!empty($obj))
        {
             $packagesql = "update ns_".$class." set  `trackId` = '".$obj->trackId."',
                                                   `name` = '".$obj->name."',
                                                   `price` = '".$obj->price."',
                                                   `hours` = '".$obj->hours."',
                                                   `persons` = '".$obj->persons."',
                                                   `makeup` = '".$obj->makeup."',
                                                   `type` = '".$obj->type."',
                                                   `orderInc` = '".$obj->orderInc."'
                                              where  e_oid = '".$obj->e_oid."'";    
             if (!empty($debug))
             {
                 echo $packagesql."\n";
             }else{
                 sql_execute($packagesql);
                 $package_id = $obj->e_oid;                  
             } 

           /**
            * delete start
            */  
                $original_packageitem_id = getsonid('ns_v1packageitem','e_oid','package_id',$obj->e_oid);//原来的packageitem_id数组
                 
                if(!empty($debug))
                {
                   print_r($original_packageitem_id); 
                }       
             
               $new_packageitem_id = array();
               
               foreach($obj->packageItems as $pitem1)
               {
                    $new_packageitem_id[] = $pitem1->e_oid;
               }

               $delete_packageitem_id = array_diff($original_packageitem_id, $new_packageitem_id);//需要delete 的packageitem_id
               
               if(!empty($delete_packageitem_id))
               {
                    foreach($delete_packageitem_id as $deleteid)
                    {
                         $pitemselect_id = getsonid('ns_v1packageitemselect','e_oid','packageitem_id',$deleteid); 
                         
                              if(!empty($pitemselect_id))
                               {                          
                                     foreach($pitemselect_id as $pid)
                                     {
                                         $pitemselectlsql = "delete from ns_v1packageitemselect where e_oid = '".$pid."' ";
                                         sql_execute($pitemselectlsql); 
                                     }
                               }//
                            
                        $packageitemsql = "delete from ns_v1packageitem where e_oid = '".$deleteid."' ";
                        sql_execute($packageitemsql);                       
                    
                    }
                }//delete packitems end                 
             /**
              * delete end
              */
            
             if(!empty($obj->packageItems))
             {
             
                foreach($obj->packageItems  as $pitem)
                {
                	// delete select start
                     if(!empty($pitem->sample->attributes)) 
                     {
		                $original_piselect_id = getsonid('ns_v1packageitemselect','e_oid','packageitem_id',$pitem->e_oid);//原来的piselect_id数组
		                 
		                if(!empty($debug))
		                {
		                   print_r($original_piselect_id); 
		                }       
		             
		                $new_piselect_id = array();
		               
		                foreach($pitem->selects as $piselect1)
		                {
		                    $new_piselect_id[] = $piselect1->e_oid;
		                }
		
		                $delete_piselect_id = array_diff($original_piselect_id, $new_piselect_id);//需要delete 的piselect_id    

		                if(!empty($delete_piselect_id))
		                {
		                	foreach ($delete_piselect_id as $dpi_id)
		                	{
                                 $pitemselectlonesql = "delete from ns_v1packageitemselect where e_oid = '".$dpi_id."' ";
                                 sql_execute($pitemselectlonesql); 		                		
		                	}
		                }
                     	
                     }else{//删除已经错误增加的所有select
                        $pitemselectlallsql = "delete from ns_v1packageitemselect where packageitem_id = '".$pitem->e_oid."' ";
                        sql_execute($pitemselectlallsql);                     	
                     }           	 
                 	
                	//delete select end
                	
                     if(isset($pitem->id) || isset($pitem->e_oid))
                     {//update
                     
                         $purchaseitemsql = "update ns_".$class."item set `trackId` = '".$pitem->trackId."',
                                                                          `quantity` = '".$pitem->quantity."',
                                                                          `total` = '".$pitem->total."',
                                                                          `otherId` = '".$pitem->otherId."',
                                                                          `sample_id` = '".$pitem->sample->id."',
                                                                          `package_id` = '".$package_id."'
                                                                    where  e_oid = '".$pitem->e_oid."'";
                         if (!empty($debug))
                         {
                             echo $purchaseitemsql."\n";
                         }else{
                             sql_execute($purchaseitemsql);
                             $purchaseitem_id = 0;
                             $purchaseitem_id = $pitem->e_oid;                               
                         }                                          
                         
                     }else{//add
                     
                             $purchaseitemsql = "insert into ns_".$class."item (`e_oid`,`trackId`,`quantity`,`total`,`otherId`,`sample_id`,`package_id`) values 
                                                                (NULL,'".$pitem->trackId."','".$pitem->quantity."','".$pitem->total."',
                                                                '".$pitem->otherId."','".$pitem->sample->id."','".$package_id."')";  
                             if (!empty($debug))
                             {
                                 echo $purchaseitemsql."\n";
                                 $purchaseitem_id = 0; 
                             }else{
                                 sql_execute($purchaseitemsql);
                                 $purchaseitem_id = lastinsertid();                          
                             } 
                                                                                        
                                 
                     }//purchaseitem add   

                     
                     if(!empty($pitem->selects) && !empty($pitem->sample->attributes))
                     {
                        foreach($pitem->selects  as $pselect)
                        {
                            if (isset($pselect->id) || isset($pselect->e_oid))
                            {//pselect update
                                         
                                 $pselectsql = " update ns_".$class."itemselect set `trackId` = '".$pselect->trackId."',
                                                                                    `title` = '".$pselect->title."',
                                                                                    `value` = '".$pselect->value."',
                                                                                    `packageitem_id` = '".$purchaseitem_id."' 
                                                                              where  e_oid = '".$pselect->e_oid."'";
                                  if (!empty($debug))
                                  {
                                         echo $pselectsql."\n";               
                                  }else{
                                          sql_execute($pselectsql);       
                                  }         

                            }else{//pselect add
                            
                                 $pselectsql = "insert into ns_".$class."itemselect(`e_oid`,`trackId`,`title`,`value`,`packageitem_id`) values
                                                                                   (NULL,'".$pselect->trackId."','".$pselect->title."','".$pselect->value."',
                                                                                   '".$purchaseitem_id."')";                            
                                  if (!empty($debug))
                                  { 
                                     echo $pselectsql."\n";
                                  }else{
                                      sql_execute($pselectsql);          
                                  }
                              
                            }//end add   
                        }
                        
                     }//$purchaseitemselcts not null                           
                                               
                                         
                }//end pitems     
             }
            
        }//obj not null         
                
    
    }

/**
 * expense add
 */
 
         function pdoexpenseadd($obj,$class,$debug=''){
                                                           
             if(!empty($debug))
             {
                print_r($obj);
             }
             
             if(!empty($obj))
             {  
                $expensevalue = '';
                $fieldsexpense = '';
                
                foreach($obj as $key => $value)
                {
                    if(!in_array($key,array('cancelledMessage')))
                     {
                         $fieldsexpense.= '`'.$key.'`,';
                         
                         if( in_array($key,array('createdDate','payDate','cancelledDate','confirmDate') ) )  $value = SimpleDate::toStamp($value);
                         
                         $expensevalue .=" '".addslashes($value)."',";                   
                     }                    
                }
                
                $fieldsexpense .= "cancelledMessage";
                $expensevalue .= "'0'";
                
                $expensesql = " insert into ns_".$class."(e_oid,".$fieldsexpense.") values(NULL,".$expensevalue.")";
                
                if(!empty($debug))
                {
                    echo "EXECUTE SQL:\n".$expensesql."\n";     
                }else{
                    sql_execute($expensesql);
                }
                
                
             }//not null                                                           
                                                           
                                                           
         }
    
/*
 *add payments
 */
function pdov1paymentadd($obj,$class,$debug=''){
 

                                        
                       foreach($obj->payments  as $payment){
                       
                             
                            if(isset( $payment->e_oid ) || isset( $payment->e_oid )){
                              continue;
                            }
                                   $addsqlpayment = '';
                                   $fieldspayment = '';                           
                                  foreach($payment as $key => $value){
                                  

                                        
                                        if(!in_array($key , array('customerId','orderId'))){

                                            $fieldspayment.= '`'.$key.'`,';
                                            if(in_array($key,array('createdDate','date','cancelledDate')) )   $value = SimpleDate::toStamp($value);                                  
                                            $addsqlpayment.=" '".addslashes($value)."',";
                                        }
                                        
                                    }                           
                                    
                                
                                 $fieldspayment .='customerId,orderId';
                            
                                 $addsqlpayment .="'".$obj->customerId."','".$obj->e_oid."'"; 
                                
                                 $paymentsql="insert into ns_v1payment (e_oid,".$fieldspayment.") values(NULl,".$addsqlpayment.")";                         
                                  
                                 
                                   if(!empty($debug)){
                                     echo $paymentsql.'<br>';
                                   }else{   
                                      sql_execute($paymentsql);
                                   }                                 
                                 unset($key);
                                 unset($value);                                 
                        
                        
                       }//end payments         
   

}
  
    
function pdoupdate($obj,$class,$debug=''){
	
    
    $id=$obj->id;
    
    switch ($class)
    {
    	case 'payment':
    		$tbname = 'v1payment';
    		break;
    		
    	default:
    		$tbname = $class;	
    		break;
    }
    
    $upsql="update ns_".$tbname." set ";
    
    foreach ($obj as $key => $value){
        
        if(!in_array($key ,array('id','e_oid','_text') ))
        {
        	if(in_array($key,array('createdDate','date','cancelledDate')))
        	{
	        	if(is_object($obj->$key))
	        	{
	        		$value = SimpleDate::toStamp($value);
	        		if(empty($value)) $value = 0;
	         	}else{
	         		if(empty($obj->$key)) $value = 0;
	         	}
        	}
         	
            $upsql.= '`'.$key."`='".addslashes($value)."',";
        }
        
    }
    
    
    $upsql =substr($upsql,0,-1);
    $upsql.=" where e_oid='".$id."'";
    
    if(!empty($debug))
    {
    	echo $upsql;
    }else{
    	sql_execute($upsql);
    }
    
    
    
}

/**
 * @param $obj
 * @param $class
 * @param $debug=''是否开始调试模式，,
 * @param $excustomer=''是否只执行customer
 */

function pdov1customerupdate($obj,$action,$debug='',$excustomer=''){
    
    if(!empty($debug)){
       print_r($obj);
    }
    
    if(!empty($obj)){
    
            $customersql = "update ns_".$action." set " ;
            foreach($obj as $key => $value)
            {
               if(!in_array($key,array('id','e_oid','orders','createdDate','cancelledDate','_text') ))
               {
                  $customersql.= '`'.$key."`='".addslashes($value)."',";
               }
            }//get all fields
            
            $customersql = substr($customersql,0,-1);
            $customersql.= " where e_oid = ".$obj->id." ";

            if(!empty($debug)){
                 echo "customer update Execute SQL:\n".$customersql."\n";
            }else{
                 sql_execute($customersql);
                 $customer_id = $obj->id;
            }       

             unset($key);
             unset($value);
             
           if(empty($excustomer))
           {  
           /**
            *order add(update)
            */
            if(!empty($obj->orders)){
            
                $original_order_id = getsonid('ns_v1myorder','e_oid','customerId',$obj->id);//原来的order_id数组
                 
                if(!empty($debug))
                {
                   print_r($original_order_id); 
                }       
             
               $new_order_id = array();
               
               foreach($obj->orders as $order1)
               {
                    $new_order_id[] = $order1->e_oid;
               }

               $delete_order_id = array_diff($original_order_id, $new_order_id);//需要delete 的order_id
               
               if(!empty($delete_order_id))
               {
                    foreach($delete_order_id as $deleteid)
                    {
                         $pitem_id = getsonid('ns_v1purchaseitem','e_oid','order_id',$deleteid); 
                         
                              if(!empty($pitem_id))
                               {                          
                                     foreach($pitem_id as $pid)
                                     {
                                        $pselect_id = getsonid('ns_v1purchaseitemselect','e_oid','purchaseitem_id',$deleteid,'','1'); 
                                        
                                         if(!empty($pselect_id))
                                         {
                                             $pselectdelsql = "delete from ns_v1purchaseitemselect where e_oid in (".$pselect_id.")"; 
                                             sql_execute($pselectdelsql); 
                                         }
                                         
                                         $pnote_id = getsonid('ns_v1purchasenote','e_oid','purchaseitem_id',$deleteid,'','1');
                                         if(!empty($pnote_id))
                                         {
                                             $pnotedelsql = "delete from ns_v1purchasenote where e_oid in (".$pnote_id.")"; 
                                             sql_execute($pnotedelsql); 
                                         }
                                         
                                         $pitemdelsql = "delete from ns_v1purchaseitem where e_oid = '".$pid."' ";
                                         sql_execute($pitemdelsql); 
                                     }
                         }//
                         
                            
                        $orderdelsql = "delete from ns_v1myorder where e_oid = '".$deleteid."' ";
                        sql_execute($orderdelsql);                      
                    
                    }
                }//delete orders end            
               
               foreach($obj->orders as $order){//many orders
                 
                  if(isset($order->e_oid) || isset($order->id) ){//update orders

                                $ordersql = 'update ns_v1myorder  set ';
                                
                                foreach($order as $key => $value){//one order
                                
                                   if(!in_array($key,array('id','e_oid','createdDate','purchaseItems','payments') ))
                                   {
                                   	   if(is_object($order->$key) )
                                   	   {
                                   	   	   $value = SimpleDate::toStamp($value); 
                                   	   	   if(empty($value)) $value = 0;
                                   	   }else{
                                   	   	   if(empty($order->$key)) $value = 0;
                                   	   }
                                     
                                       $ordersql.= '`'.$key."`='".addslashes($value)."',";
                                    
                                   }
                                
                                }//end one order
                                
                                $ordersql = substr($ordersql,0,-1);
                                $ordersql.= " where e_oid = ".$order->e_oid." ";
                                
                                if(!empty($debug)){
                                    echo "order update Execute SQL:\n".$ordersql."\n";
                                }else{
                                    sql_execute($ordersql);
                                    $orderId = $order->e_oid;
                                }
                                
                                unset($key);
                                unset($value);
                   
                 }else{//add order
                 
                             $addsqlorder = '';
                             $fieldsorder = ''; 
                                 
                                foreach ($order as $key => $value)
                                {//one orders
                                    if(!in_array($key ,array('disposaldate','disposaluserAccount','disposalstatus','disposalmessage','purchaseItems','payments',
                                                             'customerId','photo','video','disposal'))){
                                        $fieldsorder.= $key.',';
                                        if( in_array($key,array('createdDate','date','disposaldate') ) )
                                        {
                                        	if(is_object($order->$key))
                                        	{
                                        		$value = SimpleDate::toStamp($value); //把日期转化为时间戳
                                        	}else{
                                        		if(empty($order->$key)) $value = 0;
                                        	}
                                        }
                                        $addsqlorder.=" '".addslashes($value)."',";
                                    
                                    }
                                    

                                }
                                    $fieldsorder .='customerId,disposalstatus';
                                    $addsqlorder .="'".$customer_id."','0'"; 
                                    $ordersql="insert into ns_v1myorder (e_oid,".$fieldsorder.") values(NULl,".$addsqlorder.")";

                                       if(!empty($debug)){
                                         echo "order add Execute SQL:\n".$ordersql."\n";
                                       }else{   
                                         sql_execute($ordersql);
                                         $orderId = lastinsertid();     
                                       }                    
                               
                                   unset($key);
                                   unset($value);                
                 
                 }//end order add
                 
                 
               /**
                *purchaseItems
                */
                 if(!empty($order->purchaseItems))
                 {
                    foreach($order->purchaseItems as $pitem)
                    {//many items
                      if(isset($pitem->e_oid) || isset($pitem->id) )
                        {//update items
                               $purchaseitemsql = "update ns_v1purchaseitem  set ";
                                foreach($pitem as $key => $value)
                                {
                                   if(!in_array($key,array('id','e_oid','selects','notes','_added')))
                                   {
                                     $purchaseitemsql.= $key."='".addslashes($value)."',";
                                   }
                                }
                                
                                $purchaseitemsql = substr($purchaseitemsql,0,-1);
                                $purchaseitemsql.= " where e_oid = ".$pitem->e_oid." ";
                                
                                if(!empty($debug))
                                {
                                    echo "purchaseitem update Execute SQL:\n".$purchaseitemsql."\n";
                                }else{
                                    sql_execute($purchaseitemsql);
                                    $purchaseitem_id = lastinsertid();
                                }
                                unset($key);
                                unset($value);  
                                
                        }else{//add items
                        
                                $addsqlpitem = '';
                                $fieldspitem = '';                            
                                  foreach($pitem as $key => $value)
                                  {
                                    if(!in_array($key ,array('selects','notes','_added','order_id')))
                                    {
                                        $fieldspitem.= $key.',';
                                        $addsqlpitem.=" '".addslashes($value)."',";
                                    }                           
                                  }//end one item
                                  
                                
                                 $fieldspitem .='order_id';
                                 $addsqlpitem .="'".$orderId."'"; 
                                 $pitemsql="insert into ns_v1purchaseitem (e_oid,".$fieldspitem.") values(NULl,".$addsqlpitem.")";                          

                                   if(!empty($debug)){
                                     echo $pitemsql.'<br>';
                                   }else{   
                                     sql_execute($pitemsql);
                                     $purchaseitem_id = lastinsertid();
                                   }                         
                                 
                                 unset($key);
                                 unset($value);                             
                            
                        }//end itemsadd
                        
                        
                        
                            /**
                             *selects
                             *
                             */
                             
                             if(!empty($pitem->selects))
                             {
                                foreach($pitem->selects as $pselect)
                                {
                                    if(isset($pselect->id) || isset($pselect->e_oid))
                                    {//update select
                                           $pselectsql = 'update ns_v1purchaseitemselect  set ';
                                            foreach($pselect as $key => $value)
                                            {
                                               if(!in_array($key,array('id','e_oid')))
                                               {
                                                 $pselectsql.= $key."='".addslashes($value)."',";
                                               }
                                            }
                                            
                                            $pselectsql = substr($pselectsql,0,-1);
                                            $pselectsql.= " where e_oid = ".$pselect->e_oid." ";
                                            
                                            if(!empty($debug))
                                            {
                                                echo "purchaseitemselect update Execute SQL:\n".$pselectsql."\n";
                                            }else{
                                                sql_execute($pselectsql);
                                                //$purchaseitem_id = lastinsertid();
                                            }
                                            unset($key);
                                            unset($value);                                         
                                       
                                    }else{//add select
                                            $addsqlpis = '';
                                            $fieldspis = '';                              
                                            foreach($pselect as $key => $value)
                                                {
                                                    if(!in_array($key ,array('purchaseitem_id')))
                                                    {
                                                        $fieldspis.= $key.',';
                                                        $addsqlpis.=" '".addslashes($value)."',";
                                                    }
                                                }    
                                                                                
                                             $fieldspis .='purchaseitem_id';
                                             $addsqlpis .="'".$purchaseitem_id."'"; 
                                                     
                                             $pissql="insert into ns_v1purchaseitemselect (e_oid,".$fieldspis.") values(NULl,".$addsqlpis.")";                          
                                                      
                                                if(!empty($debug))
                                                {
                                                    echo "purchaseitemselect update Execute SQL:\n".$pissql."\n";
                                                }else{   
                                                    sql_execute($pissql);
                                                }
                                                
                                                unset($key);
                                                unset($value);                                          
                                    
                                    
                                    }//end select                                   
                                }
                             }//selects not null
                             
                             
                            /**
                             *notes
                             *
                             */ 

                             if(!empty($pitem->notes))
                             {
                                foreach($pitem->notes as $pnote)
                                {
                                    if(isset($pnote->id) || isset($pnote->e_oid))
                                    {//update note
                                           $pnotesql = 'update ns_v1purchasenote  set ';
                                            foreach($pnote as $key => $value)
                                            {
                                               if(!in_array($key,array('id','e_oid')))
                                               {
                                               	 if(is_object($pnote->$key))
                                               	 {
                                               	 	$value = SimpleDate::toStamp($value);
                                               	 	if(empty($value)) $value = 0;
                                               	 }else{
                                               	 	if(empty($pnote->$key)) $value = 0;
                                               	 }
                                                 $pnotesql.= $key."='".addslashes($value)."',";
                                               }
                                            }
                                            
                                            $pnotesql = substr($pnotesql,0,-1);
                                            $pnotesql.= " where e_oid = ".$pnote->e_oid." ";
                                            
                                            if(!empty($debug))
                                            {
                                                echo "purchasenote update Execute SQL:\n".$pnotesql."\n";
                                            }else{
                                                sql_execute($pnotesql);
                                                //$purchaseitem_id = lastinsertid();
                                            }
                                            unset($key);
                                            unset($value);                                         
                                       
                                    }else{//add note
                                            $addsqlnote = '';
                                            $fieldsnote = '';                             
                                            foreach($pnote as $key => $value)
                                                {
                                                    if(!in_array($key ,array('purchaseitem_id')))
                                                    {
                                                        $fieldsnote.= $key.',';
                                                        
                                                        if(in_array($key,array('date')))
                                                        {
                                                        	if(is_object($pnote->$key))
                                                        	{
                                                        		$value = SimpleDate::toStamp($value);
                                                        		if(empty($value)) $value = 0;
                                                        	}else{
                                                        		if(empty($pnote->$key)) $value = 0;
                                                        	}
                                                        }
                                                        $addsqlnote.=" '".addslashes($value)."',";
                                                    }
                                                }    
                                                                                
                                             $fieldsnote .='purchaseitem_id';
                                             $addsqlnote .="'".$purchaseitem_id."'"; 
                                                     
                                             $pissql="insert into ns_v1purchasenote (e_oid,".$fieldsnote.") values(NULl,".$addsqlnote.")";                          
                                                      
                                                if(!empty($debug))
                                                {
                                                    echo "purchasenote update Execute SQL:\n".$pissql."\n";
                                                }else{   
                                                    sql_execute($pissql);
                                                }
                                                
                                                unset($key);
                                                unset($value);                                          
                                    
                                    
                                    }//end note                                     
                                }
                             }//notes not null                           
                        
                    }//end foreach items
                     
                        
                     
                     }//itmes not null 
                                                     
                    

               }//end foreach orders
            
            
            }//order not null
            
          }//是否只执行customer
    }   
    

	
}

/**
 * cancel orders
 * @param unknown_type $obj
 * @param unknown_type $class
 */

function pdov1myorderupdate($obj,$class,$debug=''){
    
    if(!empty($debug))
    {
        print_r($obj);  
    }         
    
    if(!empty($obj))
    {      
            $upsql="update ns_".$class." set disposaldate = '".SimpleDate::toStamp($obj->disposaldate)."',
                                             disposaluserAccount = '".$obj->disposaluserAccount."', 
                                             disposalstatus = '".$obj->disposalstatus."',
                                             disposalmessage = '".addslashes($obj->disposalmessage)."'
                                       where e_oid ='".$obj->e_oid."'";
            
            if(!empty($debug))
            {
                echo $upsql."\n";               
            }else{
                sql_execute($upsql);      
            }
    }
}


/**
 *close order
 *
 */
 
 function pdov1myorderclose($obj,$class,$debug='')
 {
    $result = new stdClass();
    $result->data = array(); 
  
    if(!empty($debug))
    {
        print_r($obj);  
    }         
    
    if(!empty($obj))
    {      
            $upsql="update ns_".$class." set finished = '".$obj->finished."' where e_oid ='".$obj->e_oid."'";
            
            if(!empty($debug))
            {
                echo $upsql."\n";               
            }else{
                sql_execute($upsql);      
            }                    
    }
    $result->data[] = $obj;
    echo json_encode($result);
 
 
 }

/**
 *cancel payment
 *
 */
 
 function pdov1paymentupdate($obj,$class){

 	
    $upsql="update ns_".$class." set cancelled = '".$obj->cancelled."',
                                     cancelledDate = '".SimpleDate::toStamp($obj->cancelledDate)."', 
                                     cancelledOperator = '".$obj->cancelledOperator."',
                                     cancelledMessage = '".addslashes($obj->cancelledMessage)."'
                               where e_oid ='".$obj->e_oid."'";

    sql_execute($upsql);                           
 }

 
 
 /**
  *cancel  expense 
  *
  */
  function pdoexpenseupdate($obj,$class,$debug='')
  {
        if(!empty($debug))
        {
            print_r($obj);     
        }

        if(!empty($obj))
        {
                   
            $upsql="update ns_".$class." set status = '".$obj->status."',
                                             cancelledDate = '".SimpleDate::toStamp($obj->cancelledDate)."', 
                                             cancelledOperator = '".$obj->cancelledOperator."',
                                             cancelledMessage = '".addslashes($obj->cancelledMessage)."'
                                       where e_oid ='".$obj->e_oid."'";     
        
            sql_execute($upsql);
        }       
  
  }


function pdoremove($obj,$class){
    
    $id = $obj->id;
    $delsql="delete from ns_".$class." where e_oid='".$id."'";
    
    sql_execute($delsql);
    
}

    /*
     *package delete
     *
     */
     function pdov1packagemove($obj,$class,$debug='')
     {
            if(!empty($obj))
            {
                 if(!empty($debug))
                {
                     print_r($obj);  
                }

                 $packageitem_id = getsonid('ns_v1packageitem','e_oid','package_id',$obj->e_oid);
                 
                 if(!empty($packageitem_id))
                 {
                     foreach($packageitem_id  as $deleteid)
                     {
                         $pitemselect_id = getsonid('ns_v1packageitemselect','e_oid','packageitem_id',$deleteid); 
                         
                              if(!empty($pitemselect_id))
                               {                          
                                     foreach($pitemselect_id as $pid)
                                     {
                                         $pitemselectlsql = "delete from ns_v1packageitemselect where e_oid = '".$pid."' ";
                                         
                                         if (!empty($debug))
                                         {
                                             echo $pitemselectlsql."\n";
                                         }else{
                                             sql_execute($pitemselectlsql);  
                                         }
                                     }
                               }//  

                         $packageitemsql = "delete from ns_v1packageitem where e_oid = '".$deleteid."' ";
                        
                        if (!empty($debug))
                        {
                             echo $packageitemsql."\n";        
                        }else{
                             sql_execute($packageitemsql);
                        }
                                                           
                     }      
                 }
                                 
                
                 $packageql = "delete from ns_v1package where e_oid = '".$obj->e_oid."' ";
                 if (!empty($debug))
                 {
                     echo $packageql."\n";
                 }else{
                     sql_execute($packageql); 
                 }
                
            }// end not null   
        
     
     }
     
     
     /**
      * 
      *pdoepurchaseitemupdate operate 
      */
     function pdopurchaseitemupdate($obj,$class,$debug='')
     {
        if (!empty($debug))
        {
            print_r($obj);
        }
        
        if(!empty($obj->notes))
        {
            foreach ($obj->notes as $note)
            {
                if(isset($note->id) || isset($note->e_oid))
                {//update
                    
                    
                    
                }else{//add
                    $purchasenotesql = "insert into ns_v1purchasenote (e_oid,trackId,author,date,content,cancelled,purchaseitem_id) values(NULL,'".$note->trackId."','".$note->author."',
                                                                     '".SimpleDate::toStamp($note->date)."','".addslashes($note->content)."','".$note->cancelled."','".$obj->id."')";
                    if (!empty($debug))
                    {
                        echo $purchasenotesql."\n";
                    }else{
                        sql_execute($purchasenotesql);
                    }
                }
                
            }
            
        }
        
     }
     
    /**
     * pdopurchasenote
     * 
     */ 
     function pdopurchasenote($obj,$class,$debug='')
     {
        if(!empty($debug))
        {
            print_r($obj);
        }
        if(!empty($obj))
        {
            $sql = "update  ns_".$class." set `cancelled` ='".$obj->cancelled."' where e_oid = '".$obj->e_oid."'";
            
            sql_execute($sql);
            
        }
        
     }
     

     
     /**
      * 
      * delete 
      */
     function pdov1samplemove($obj,$class,$debug='')
     {
     	if(!empty($debug))
     	{
     		echo "以下为删除操作:"."\n";
     		echo "*******************tablename:".$class."*******************";
     		echo "\n";
     		print_r($obj);
     	}
     	
     	
     	if(!empty($obj))
     	{
     		//getsonid('ns_v1packageitemselect','e_oid','packageitem_id',$deleteid)
     		$attribute_id = getsonid('ns_v1sampleattribute','e_oid','sample_id',$obj->e_oid);
     		
     		
     		if(!empty($attribute_id) )
     		{
     			foreach($attribute_id as $attribute)
     			{
     				$attributeoptionids = getsonid('ns_v1sampleattributeoption','e_oid','sampleattribute_id',$attribute);
     				
     				if(!empty($attributeoptionids))
     				{
     					foreach($attributeoptionids as $attributeoption)
     					{
     						$deleteoption  = "delete from ns_v1sampleattributeoption where e_oid = '".$attributeoption."'";
     						
     						if(!empty($debug))
     						{
     							echo $deleteoption."\n";
     						}else{
     							sql_execute($deleteoption);
     						}
     					}
     				}
     				
     				$deleteattribute = "delete from ns_v1sampleattribute where e_oid = '".$attribute."'";
     				
     				if(!empty($debug))
     				{
     					echo $deleteattribute."\n";
     					
     				}else{
     					sql_execute($deleteattribute);
     				}
     				
     			}
     		}
     		
     		$deletesample = "delete from ns_v1sample where e_oid = '".$obj->e_oid."'";
     		
     		if(!empty($debug))
     		{
     			echo $deletesample."\n";
     		}else{
     			sql_execute($deletesample);
     		}
     		
     		
     		
     	}
     	
     	
     }

     
/**
 * pdoexpenseupdateall 
 */     
     function pdoexpenseupdateall($obj,$class,$debug='')
     {
     	if(!empty($debug))
     	{
     		print_r($obj);
     	}
     	
     	if(!empty($obj))
     	{
     		$expensesql = "update ns_expense set ";
     		
     		foreach ($obj as $key => $value)
     		{
     			if(!in_array($key,array('id','e_oid','_text')))
     			{
     				if(in_array($key,array('createdDate','payDate','cancelledDate','confirmDate')))
     				{
     					if(is_object($obj->$key))
     					{
     						$value = SimpleDate::toStamp($value);
     						if(empty($value)) $value = 0;
     					}else{
     						if(empty($obj->$key)) $value = 0;
     					}
     				}
     				
     				$expensesql.= '`'.$key."`='".addslashes($value)."',";
     				
     			}
     			
     		}
     		
             $expensesql = substr($expensesql,0,-1);
             $expensesql.= " where e_oid = ".$obj->e_oid." ";
                                
             if(!empty($debug)){
                echo "order update Execute SQL:\n".$expensesql."\n";
             }else{
                sql_execute($expensesql);
             }
                                
            unset($key);
            unset($value);     		
     	}
     }
     

  /**
   * pdov1paymentnoteupdate
   */    
     function pdov1paymentnoteupdate($obj,$class,$debug='')
     {
     	if(!empty($debug))
     	{
     		print_r($obj);
     	}
     	
     	if(!empty($obj))
     	{
     		$updatepayment = "update ns_v1payment set ";
     		foreach ($obj as $key => $value)
     		{
     			if(!in_array($key,array('id','e_oid','_text')))
     			{
     				if(in_array($key,array('createdDate','date','cancelledDate','')))
     				{
     					if(is_object($obj->$key))
     					{
                            $value = SimpleDate::toStamp($value);
                            if(empty($value)) $value = 0;
     					}else{
     						if(empty($obj->$key)) $value = 0;
     					}
     				}
     				
     				$updatepayment.= '`'.$key."`='".addslashes($value)."',";
     			}
     		}
     		
             $updatepayment = substr($updatepayment,0,-1);
             $updatepayment.= " where e_oid = ".$obj->e_oid." ";
                                
             if(!empty($debug)){
                echo "order update Execute SQL:\n".$updatepayment."\n";
             }else{
                sql_execute($updatepayment);
             }
                                
            unset($key);
            unset($value);      		
     		
     	}
     	
     }
     
/**
 * pdov1paymentupdate
 */     
     function paymentadd($obj,$class,$debug='')
     {
     	if(!empty($debug))
     	{
     		print_r($obj->payments);
     	}
     	
     	if(!empty($obj->payments))
     	{
     		foreach ($obj->payments as $payments)
     		{
     			if(isset($payments->e_oid) || isset($payments->id))
     			{
     				continue;
     			}
	     		$paymentfield = '';
	     		$paymentvalue = '';
	     		
	     		foreach ($payments as $key => $value)
	     		{
	     			if(!in_array($key,array('orderId')))
	     			{
		     			$paymentfield .= '`'.$key.'`,';
		     			
		     			if(in_array($key,array('createdDate','date','cancelledDate')))
		     			{
		     				if(is_object($payments->$key))
		     				{
		                        $value = SimpleDate::toStamp($value);
		                        if(empty($value)) $value = 0;
		     				}else{
		     					if(empty($payments->$key)) $value = 0;
		     				}
		     				
		     			}
		     			
		     			$paymentvalue.=" '".addslashes($value)."',";
	     			}
	     		}
	     		
	     		 $paymentfield .= "`orderId`";
	             $paymentvalue .= $obj->e_oid;
	             
	             $paymentsql = "insert into ns_v1payment(`e_oid`,".$paymentfield.") values(NULL,".$paymentvalue.")";
	             
	             if(!empty($debug))
	             {
	             	echo $paymentsql."\n";
	             }else{
	             	sql_execute($paymentsql);
	             }
     		
     		
     		}
     		
     	}//not null
     	
     	
     }
     
     /**
      * myordernoteadd
      */
     function myordernoteadd($obj,$class,$debug='')
     {
     	if(!empty($debug))
     	{
     		print_r($obj);
     	}
     	
     	if(!empty($obj))
     	{
     		$myordernotefield ='';
     		$myordernotevalue = '';
     		
     		foreach ($obj as $key => $value)
     		{
     			if(!in_array($key,array('_text')))
     			{
     				$myordernotefield .= '`'.$key.'`,';
     				$myordernotevalue.=" '".addslashes($value)."',";
     			}
     			
     		}
     		
            $myordernotefield = substr($myordernotefield,0,-1);
            $myordernotevalue = substr($myordernotevalue,0,-1);
                 
            $myordernotesql = "insert into ns_myordernote(`e_oid`,".$myordernotefield.") values(NULL,".$myordernotevalue.")";

            if(!empty($debug))
            {
            	echo $myordernotesql."\n";
            }else{
            	sql_execute($myordernotesql);
            }
            
     	}
     	
     	
     }
     
     
/**
 * pdoecnupdate
 */
 function pdoecnupdate($obj,$class,$debug='1')
 {
 	
 	
 }     
 
 
 /**
  * 
  * sendemail
  * 
  * obj
  * 
  * stdClass Object
  *(
  *  [to] => ns.lanbinbin@gmail.com
  *  [subject] => 主题
  *  [comment] => asdffffffffff
  *)
  * 
  */
 function sendemail($obj,$class,$debug='')
 {
 	
 	if(!empty($debug))
 	{
 		print_r($obj);
 		die;
 	}
 	
 	if($obj->noemail == 0)
 	{
	 	if(!empty($obj->to))
	 	{
	 	   $toarray = explode(";", $obj->to);
	 	   
	 	   foreach ($toarray as $oneto)
	 	   {
	 	   	  //$obj->subject = $fromuser=iconv("GBK","UTF-8",$obj->subject);
	 	   	  sendEmailOperate($oneto,$obj->subject,$obj->comment);
	 	   }
	 		
	 	}
 	}
 	
 	
 	
 	
 	
 	
 	
     	
 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
     
     
     
     
     
     
     
     
     
     
     
?>